package com.pucong.gitee.database.backup.business.sys.service;

import com.pucong.gitee.database.backup.common.entity.sys.vo.WebSocketReturnVo;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.utils.ApplicationContextUtil;
import com.pucong.gitee.database.backup.utils.GetTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class GetLogFileContentServiceImpl implements GetLogFileContentService {

    @Override
    public WebSocketReturnVo getLogFile(String fileName, Integer startLine, Integer maxLine) {
        WebSocketReturnVo webSocketReturnVo = new WebSocketReturnVo();
        String filePath = ApplicationContextUtil.getSystemBasePath() + File.separator + "logs" + File.separator + fileName;
        File file = new File(filePath);
        int totalLines = 0;
        try {
            totalLines = getTotalLines(file);
        } catch (IOException e) {
            webSocketReturnVo.setCurrentLine(startLine);
            webSocketReturnVo.setContent("获取总行数失败");
            return webSocketReturnVo;
        }

        if (startLine < 0) {
            startLine = totalLines + startLine;
        }
        StringBuilder out = new StringBuilder();
        try (FileReader in = new FileReader(file); LineNumberReader reader = new LineNumberReader(in)) {
            String s = "";

            int currentLine = 0;
            reader.setLineNumber(startLine);
            while ((s = reader.readLine()) != null && currentLine <= startLine + maxLine) {
                if (currentLine >= startLine) {
                    out.append(s).append("\n");
                }
                currentLine++;
            }
        } catch (IOException e) {
            throw new BusinessException("下載失敗");
        }
        String result = out.toString();
        webSocketReturnVo.setContent(result);
        if (StringUtils.isBlank(result)) {
            webSocketReturnVo.setCurrentLine(startLine);
        } else {
            webSocketReturnVo.setCurrentLine(Math.min(totalLines, (startLine + maxLine)));
        }
        return webSocketReturnVo;
    }

    /**
     * 文件内容的总行数
     */
    private static int getTotalLines(File file) throws IOException {
        FileReader in = new FileReader(file);
        LineNumberReader reader = new LineNumberReader(in);
        String s = reader.readLine();
        int lines = 0;
        while (s != null) {
            lines++;
            s = reader.readLine();
        }
        reader.close();
        in.close();
        return lines;
    }

    @Override
    public List<String> getLogFileNameList() {
        List<String> fileNameList = new ArrayList<>();
        String usrdir = System.getProperty("user.dir");
        String filePath = usrdir + File.separator + "data" + File.separator + "logs";
        File file = new File(filePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File file1 : files != null ? files : new File[0]) {
                fileNameList.add(file1.getName());
            }
        }
        fileNameList.sort((o1,o2)->{
            return o1.compareToIgnoreCase(o2);
        });
        return fileNameList;
    }

    @Override
    public void downloadLogFile(HttpServletResponse response, String fileName) {
        try (OutputStream os =response.getOutputStream()){
            response.reset();
            //首先设置响应的内容格式是force-download，那么你一旦点击下载按钮就会自动下载文件了
            response.setContentType("application/force-download");

            //通过设置头信息给文件命名，也即是，在前端，文件流被接受完还原成原文件的时候会以你传递的文件名来命名
            // 设置文件名 支持中文 采用中文文件名需要在此处转码
            fileName = new String(fileName.getBytes("GBK"), "ISO_8859_1");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buff = new byte[1024];
            String usrdir = System.getProperty("user.dir");
            String filePath = usrdir + File.separator + "data" + File.separator + "logs" + File.separator + fileName;
            File file = new File(filePath);
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))){
                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, buff.length);
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                throw new BusinessException("下載失敗");
            }
            os.flush();
        } catch (Exception e) {
            log.error("download fail", e);
            throw new BusinessException("download fail");
        }
    }

    @Override
    public void deleteLogFile() {
        String usrdir = System.getProperty("user.dir");
        String filePath = usrdir + File.separator + "data" + File.separator + "logs";
        List<String> logFileNameList = getLogFileNameList();
        Date threeMonthTime = GetTimeUtil.getThreeMonthTime();
        for (String fileName : logFileNameList) {
            final String s = filePath + File.separator + fileName;
            final Date creatTime = getCreatTime(s);
            if(threeMonthTime.after(creatTime)){
                File file = new File(s);
                file.delete();
            }
        }
    }

    private Date getCreatTime(String filePath){
        File file = new File(filePath);
        try {
            Path path= Paths.get(filePath);
            BasicFileAttributeView basicview= Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS );
            BasicFileAttributes attr = basicview.readAttributes();
            return new Date(attr.creationTime().toMillis());
        } catch (Exception e) {
            log.error("获取创建时间失败，切换另一种方式",e);
            return new Date(file.lastModified());
        }
    }
}
